import { useEffect } from 'react'
import { Modal as AntdModal,  Form, Input, message } from 'antd'
import { useRequest } from 'umi'
import moment from 'moment'
import { setFieldAdaptor, submitFieldsAdaptor } from '../helper'
import FormBuilder from '../builder/FormBuilder'
import ActionBuilder from '../builder/ActionBuilder'



const Modal = ({ modalVisible, hideModal, modalUrl }: {modalVisible: boolean; hideModal: (reload?: boolean) => void; modalUrl: string}) => {
  const init = useRequest<{data: BasicListApi.PageData}>(
    `https://public-api-v2.aspirantzhang.com${modalUrl}?X-API-KEY=antd`,
    {
      manual: true,
      onError: () => {
        hideModal()
      }
    })
  const request = useRequest((values: any) => {
    message.loading({content: '处理中，请稍等', key: 'process', duration: 0})
    const { uri, method, ...formValues } = values
    return {
      url: `https://public-api-v2.aspirantzhang.com${uri}`,
      method,
      data: { //如果用data，就可以不用JSON.stringify。如果是body必须用
        ...submitFieldsAdaptor(formValues),
        'X-API-KEY': 'antd',
      }
    }
  },
  {
    manual: true,
    onSuccess: (data) => {
      message.success({
        content: data.message,
        key: 'process',
        duration: 20
      })
      hideModal(true)
    },
    formatResult: res => {
      return res
    }
  })
  const [form] = Form.useForm()

  const onOk = (record: any) => {
    console.log(record)
  }
  // https://public-api-v2.aspirantzhang.com/api/admins/add


  useEffect(() => {
    if (modalVisible) {
      form.resetFields() //获取数据之前，清空数据
      init.run()
    }
  },[modalVisible])

  useEffect(() => {
    if (init.data) {
      form.setFieldsValue(setFieldAdaptor(init.data))
    }
  }, [init.data])

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
  }
  // 表单提交的函数
  const actionHandler = (action: BasicListApi.Action) => {
    switch (action.action) {
      case 'submit':
        form.setFieldsValue({uri: action.uri, method: action.method})
        form.submit()
        break;
      case 'cancel':
        hideModal();
        break
      case 'reset':
        form.resetFields();
        break
      default:
        break;
    }
  }
  const onFinish = (values: any) => {
    request.run(values)
  }


  return (
    <div>
      <AntdModal
        title={init?.data?.page?.title}
        visible={modalVisible}
        onOk={onOk}
        onCancel={() => { return hideModal() }}
        footer={ActionBuilder(init?.data?.layout?.actions[0]?.data, actionHandler, request.loading)}
        maskClosable={false}
        forceRender
      >
        <Form
          {...layout}
          form={form}
          onFinish={onFinish}
          initialValues={{
            create_time: moment(),
            update_time: moment(),
            status: true
          }}
        >
        {FormBuilder(init?.data?.layout?.tabs[0]?.data)}
        <Form.Item name="uri" key="uri" label="uri" hidden>
          <Input/>
        </Form.Item >
        <Form.Item name="method" key="method" label="method" hidden>
          <Input/>
        </Form.Item >


        </Form>

      </AntdModal>
    </div>
  )
}

export default Modal
